package com.coolingme.springcloud.sentinel;

import com.alibaba.csp.sentinel.init.InitFunc;

/**
 * 通过Sentinel的InitFuc SPI实现接口的扩展，配置限流规则
 * <p>
 * 单台机器配置
 *
 * @author wangyue
 * @date 2022/10/18 16:15
 */
public class FlowRuleInitFunc implements InitFunc {

    /**
     * Nacos 远程服务host
     */
    private final String remoteAddress = "192.168.3.21";

    /**
     * Nacos GroupID
     */
    private final String groupId = "SENTINEL_GROUP";

    private final String dataId = "spring-cloud-sentinel-example";

    @Override
    public void init() throws Exception {
        System.out.println("*********Sentinel InitFunc SPI**********");

        /*
        [
            {
                "resource":"say",
                "grade":1,
                "count":5
            }
        ]
         */
        // 从Nacos读取配置
        /*ReadableDataSource<String, List<FlowRule>> flowRuleDataSource =
                new NacosDataSource<>(remoteAddress, groupId, dataId,
                        source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
                                }
                        )
                );
        FlowRuleManager.register2Property(flowRuleDataSource.getProperty());*/

        // 本地配置
        /*List<FlowRule> flowRuleList = new ArrayList<>();
        FlowRule flowRule = new FlowRule();
        // 设置资源，@SentinelResource(value = "say")配置的值
        flowRule.setResource("say");
        // 限流阈值的类型 QPS（每秒查询率）或者并发数
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置QPS为5
        flowRule.setCount(5);
        flowRuleList.add(flowRule);
        // 加载限流规则
        FlowRuleManager.loadRules(flowRuleList);*/
    }

}
